package cn.seocoo.platform.api.controller.pay;

import cn.seocoo.platform.api.util.JSONResult;
import cn.seocoo.platform.common.pay.alipay.AliPayUtils;
import cn.seocoo.platform.common.utils.AmountUtils;
import cn.seocoo.platform.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.PaymentKit;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WeChatNotifyController
 * @description: 微信回调接口
 * @author: wujian
 * @Date: 2019-11-05 14:32
 **/
@RestController
@RequestMapping("/api/wechat")
public class WeChatNotifyController {

    private static final Logger logger = LoggerFactory.getLogger(AliPayUtils.class);

    /**
     * 小程序 支付商户key
     */
    @Value("${wechat.partnerKey}")
    private String wechatPartnerKey;



    /**
     * @return void
     * @Author WuJian
     * @Description //微信回调
     * @Date 14:33 2019/11/5
     * @Param [request, response]
     **/
    @PostMapping("/wechatPayNotify")
    @ResponseBody
    public String wechatPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.warn("-------------------->微信支付回调   开始<-------------------------");
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> parsemap = PaymentKit.xmlToMap(xmlMsg);
        logger.info("支付回调接口返回的参数" + parsemap);
        //校验返回来的支付结果,根据已经配置的密钥
        if (PaymentKit.verifyNotify(parsemap, wechatPartnerKey)) {
            // 订单支付成功 业务处理
            Map<String, Object> orderMsg = null;
            if (!StringUtils.isNull(parsemap.get("attach"))) {
                //自定义数据
                String json = parsemap.get("attach");
                //去掉反义字符串
                String str = StringEscapeUtils.unescapeJava(json);
                Map<String, Object> jsonToMap = JSONObject.parseObject(str);
                logger.info("订单支付通知自定义参数：" + str);
                orderMsg = (Map<String, Object>) jsonToMap.get("orderMsg");
            }
            // 支付请求订单号
            String orderNumber = parsemap.get("out_trade_no");
            //交易流水号
            String trade_no = parsemap.get("transaction_id");
            String totalFee = parsemap.get("total_fee");
            String cashFee = parsemap.get("cash_fee");
            logger.info("交易流水号----------->" + trade_no);
            logger.info("支付请求的订单号----------->" + orderNumber);
            logger.info("订单金额(元)----------->" + AmountUtils.changeF2Y(totalFee));
            logger.info("现金支付金额(元)----------->" + AmountUtils.changeF2Y(cashFee));
            // 通过商户订单判断是否该订单已经处理 如果处理跳过 如果未处理先校验sign签名 再进行订单业务相关的处理
            // 返回的签名
            parsemap.remove("sign");
            logger.info("<-----执行回调接口中自己的业务操作开始------->");
            //执行自己的业务操作->修改订单状态
            String userCode = orderMsg.get("userCode").toString();
            //订单类型->key 区分
            Object key = orderMsg.get("key");
            //------------------------------------------------------------->
            String type = null;
            String remark = null;


            return "success";
        }
        return "fail";
    }

    /**
     * @return cn.seocoo.platform.common.core.domain.AjaxResult
     * @Author WuJian
     * @Description //支付结果查询
     * @Date 14:59 2019/11/5
     * @Param [param]
     **/
    @PostMapping("/weChatResult")
    public JSONResult searchPayResult(@RequestBody ModelMap modelMap) {
        try {
            Object orderNo = modelMap.get("orderNumber");
            Object orderType = modelMap.get("orderType");
            String orderNumber = null;
            Map<String, Object> resMap = null;

            Map<String, Object> resultMap = new HashMap<String, Object>();
            //查询订单信息


            return JSONResult.ok(resMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return JSONResult.errorMsg("订单异常");
        }


    }
}
